<template>
  <div style="height: calc(100vh - 50px)">
    <q-table
      id="tablePdf"
      class="no-border-radius full-height"
      :rows="logList"
      :columns="columns"
      row-key="id"
      :pagination="{ rowsPerPage: 100 }"
      :dark="ui.isDark"
      :class="
        ui.isDark
          ? 'my-sticky-header-table-black'
          : 'my-sticky-header-table-white'
      "
    >
      <template v-slot:top v-if="$q.screen.gt.sm">
        <div class="row full-width">
          <div class="flex items-center q-gutter-x-sm">
            <q-select
              v-if="mode === 'server'"
              outlined
              :label="$t('logIndex.设备选择')"
              v-model="interval"
              :options="options"
              multiple
              dense
              :display-value="`${$t('logIndex.设备已选择')}  ${
                interval.length
              } ${$t('logIndex.个')}`"
            >
              <template
                v-slot:option="{ itemProps, opt, selected, toggleOption }"
              >
                <q-item v-bind="itemProps">
                  <q-item-section>
                    <q-item-label>{{ opt }}</q-item-label>
                  </q-item-section>
                  <q-item-section side>
                    <q-checkbox
                      :model-value="selected"
                      @update:modelValue="toggleOption(opt)"
                    />
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
            <time-date-picker
              dense
              outlined
              :label="$t('logIndex.开始时间')"
              v-model="param.startTime"
              :dark="ui.isDark"
            />
            <time-date-picker
              dense
              outlined
              :label="$t('logIndex.结束时间')"
              v-model="param.endTime"
              :dark="ui.isDark"
            />
            <q-btn
              no-caps
              :label="$t('logIndex.日志删除')"
              color="red-5"
              style="width: 8rem"
              @click="DeleteLog"
              v-if="
                param.startTime !== null &&
                param.endTime !== null &&
                logList.length !== 0
              "
            />
          </div>
          <q-space />
          <q-btn
            no-caps
            color="secondary"
            class="desktop-only"
            :label="$t('logIndex.导出xlsx日志')"
            @click="exportLog"
            icon="archive"
          />
          <q-btn
            no-caps
            color="secondary"
            class="mobile-only"
            :label="$t('logIndex.导出xlsx日志')"
            @click="exportLog"
            icon="archive"
          />
        </div>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td
            v-for="column in columns"
            v-bind:key="column.name"
            :props="props"
          >
            {{ props.row[column.name] }}
          </q-td>
        </q-tr>
      </template>
      <template v-slot:bottom>
        <div class="full-width flex flex-center">
          <q-pagination
            v-model="param.page"
            :max="page"
            input
            :dark="ui.isDark"
          />
          <q-btn-dropdown
            no-caps
            class="q-ml-sm"
            v-if="$q.screen.lt.md"
            color="primary"
            :label="$t('logIndex.范围筛选')"
            :menu-offset="[50, 8]"
          >
            <q-card-section class="q-gutter-y-sm q-pa-sm">
              <q-select
                v-if="mode === 'server'"
                outlined
                :label="$t('logIndex.设备选择')"
                v-model="interval"
                :options="options"
                multiple
                dense
                :display-value="`${$t('logIndex.设备已选择')}  ${
                  interval.length
                } ${$t('logIndex.个')}`"
              >
                <template
                  v-slot:option="{ itemProps, opt, selected, toggleOption }"
                >
                  <q-item v-bind="itemProps">
                    <q-item-section>
                      <q-item-label>{{ opt }}</q-item-label>
                    </q-item-section>
                    <q-item-section side>
                      <q-checkbox
                        :model-value="selected"
                        @update:modelValue="toggleOption(opt)"
                      />
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
              <time-date-picker
                dense
                outlined
                :label="$t('logIndex.开始时间')"
                v-model="param.startTime"
                :dark="ui.isDark"
              />
              <time-date-picker
                dense
                outlined
                :label="$t('logIndex.结束时间')"
                v-model="param.endTime"
                :dark="ui.isDark"
              />
              <q-btn
                no-caps
                :label="$t('logIndex.日志删除')"
                color="red-5"
                class="full-width"
                @click="DeleteLog"
                v-if="param.startTime !== null && param.endTime !== null"
              />
              <q-btn
                no-caps
                color="secondary"
                class="full-width desktop-only"
                @click="exportLog"
                :label="$t('logIndex.导出xlsx日志')"
                icon="archive"
              />
              <q-btn
                no-caps
                color="secondary"
                class="full-width mobile-only"
                @click="exportLog"
                :label="$t('logIndex.导出xlsx日志')"
                icon="archive"
              />
            </q-card-section>
          </q-btn-dropdown>
        </div>
      </template>
    </q-table>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { utils, writeFile } from "xlsx";
import { useQuasar } from "quasar";
import { api } from "boot/axios.js";
import { useAPIStore } from "stores/api/index.js";
import { useFunctionsStore } from "stores/functions/index.js";
import TimeDatePicker from "components/animations/TimeDatePicker.vue";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";

const t = useI18n().t; // 语言包
const columns = [
  { label: t("logIndex.上报日期"), align: "left", name: "date", field: "date" },
  {
    label: t("logIndex.上报设备"),
    align: "left",
    name: "device",
    field: "device",
  },
  { label: "信息来源", name: "source", align: "left", field: "source" },
  { label: t("logIndex.错误类型"), align: "left", name: "type", field: "type" },
  {
    label: t("logIndex.详细描述"),
    align: "left",
    name: "description",
    field: "description",
  },
];
const centerUrl = useAPIStore().centerUrl;
const ui = useUiStore();
const $q = useQuasar();
const param = ref({
  page: 1,
  startTime: null,
  endTime: null,
});
const logList = ref([]);
const interval = ref([]);
const options = ref([]);
const page = ref(1);
const mode = useFunctionsStore().mode;

onMounted(getLog);

watch(param, getLog, { deep: true });

watch(interval, (value) => {
  if (value !== "" && interval.value !== "") getLog();
});
// 查询日志
function getLog() {
  $q.screen.setSizes({ sm: 300, md: 500, lg: 1000, xl: 2000 });
  api
    .post(centerUrl + "log", interval.value, { params: param.value })
    .then((rs) => {
      logList.value = rs.data;
      logList.value = logList.value.filter((item) => item.type !== "disinfect");
    });
  api
    .post(centerUrl + "log/page", interval.value, { params: param.value })
    .then((rs) => {
      page.value = rs.data;
    });
  api.get(centerUrl + "log/device/all").then((rs) => {
    options.value = rs.data;
  });
}
// 删除日志
function DeleteLog() {
  $q.dialog({
    dark: ui.isDark,
    title: t("logIndex.日志删除"),
    message:
      t("logIndex.是否要删除") +
      param.value.startTime +
      t("logIndex.到") +
      param.value.endTime +
      t("logIndex.的日志"),
    ok: t("ok"),
    cancel: t("cancel"),
  }).onOk(() => {
    api
      .delete(centerUrl + "log", {
        params: {
          startTime: param.value.startTime,
          endTime: param.value.endTime,
        },
      })
      .then((rs) => {
        $q.notify({
          message: t("logIndex.日志删除成功"),
          type: "positive",
        });
        getLog();
      });
  });
}
// 导出日志
async function exportLog() {
  const workBook = utils.book_new();
  let all = [];
  const title = [
    {
      id: t("logIndex.日志ID"),
      date: t("logIndex.上报日期"),
      device: t("logIndex.上报设备"),
      source: t("logIndex.信息来源"),
      type: t("logIndex.错误类型"),
      area: t("logIndex.报警地点"),
      description: t("logIndex.详细描述"),
    },
  ];
  const dialog = $q.dialog({
    dark: ui.isDark,
    message: "Uploading... 0%",
    progress: true,
    persistent: true,
    ok: false,
  });
  let percentage = 0;
  for (let i = 0; i < page.value; i++) {
    const params = {
      page: i + 1,
      startTime: param.value.startTime,
      endTime: param.value.endTime,
    };
    const res = await api.post(centerUrl + "log", interval.value, { params });
    all = all.concat(res.data);
    percentage = Math.floor(((i + 1) / page.value) * 100);
    dialog.update({
      message: `${t("logIndex.下载中")}... ${percentage}%`,
    });
  }
  if (percentage >= 99) {
    dialog.hide();
  }
  const sheet = utils.json_to_sheet(title.concat(all), { skipHeader: true });
  utils.book_append_sheet(workBook, sheet, "Sheet");
  writeFile(workBook, `${t("logIndex.设备日志")}.xlsx`);
}
</script>

<style lang="sass">
.my-sticky-header-table-black
  /* height or max-height is important */
  height: 310px

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th
    /* bg color is important for th; just specify one */
    background-color: rgb(0, 0, 0)
    font-size: 16px

  thead tr th
    position: sticky
    z-index: 1
  thead tr:first-child th
    top: 0

  &.q-table--loading thead tr:last-child th
    top: 48px
</style>
<style lang="sass">
.my-sticky-header-table-white
  /* height or max-height is important */
  height: 310px

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th
    /* bg color is important for th; just specify one */
    background-color: rgb(255, 255, 255)
    font-size: 16px

  thead tr th
    position: sticky
    z-index: 1
  thead tr:first-child th
    top: 0

  &.q-table--loading thead tr:last-child th
    top: 48px
</style>
